package com.study.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson2.JSONObject;

import com.study.anno.SafetyProcess;
import com.study.domain.AjaxResult;
import com.study.domain.dto.User;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;


/**
 * @Author csc
 * @Description
 * @Date 2021/08/23 14:01
 */
@RestController
public class DemoController {

    /**
     * 请求参数解密，响应结果加密
     * @return
     */
    @SafetyProcess
    @PostMapping(value = "/test")
    public AjaxResult test(@RequestBody User user) {
        return AjaxResult.success(user);
    }



    /**
     * 请求参数解密
     * @param reqDTO
     * @return
     */
    @SafetyProcess(encode = false)
    @PostMapping(value = "/test2")
    public AjaxResult test2(@RequestBody User reqDTO) {
        return AjaxResult.success(reqDTO);
    }

    /**
     * 只有响应结果加密,请求参数不需要加密
     */
    @SafetyProcess(decode = false)
    @PostMapping(value = "/test3")
    public AjaxResult test3(@RequestBody User user) {
        return AjaxResult.success(user);
    }

    /**
     * 不进行加解密
     * @return
     */
    @SafetyProcess(decode = false, encode = false)
    @PostMapping(value = "/test4")
    public AjaxResult test4(@RequestBody User user) {
        return AjaxResult.success(user);
    }


    public static void main(String[] args) {
        //参数加密
         String secret = "1234567890abcdef";

        JSONObject bodyStr = new JSONObject();
        bodyStr.put("username","csc");
        bodyStr.put("password","123456");
        //aes加密
        byte[] bytes = SecureUtil.aes(secret.getBytes()).encrypt(bodyStr.toString());
        //base64编码返回
        System.out.println(Base64.encode(bytes));

        //返回参数解密 时 先进行base64解码
        String endone = "thfXbNpHKe9EYt7qJBzN/8uzeL0TO9i10FfpMZFy+PjbHmFyJYkDBkgVtjaugki1YmbZQjk4WzKVKdACL3EFtUSyZxR78Bzp319oiiUmJpo=";
        byte[] decode = Base64.decode(endone);
        //aes解密
       String jiemi = SecureUtil.aes(secret.getBytes()).decryptStr(decode);
        /**
         * 结果返回:
         * {"flag":true,"msg":"success","data":{"username":"csc","password":"123456"}}
         */
        System.out.println(jiemi);

    }

}
